"""
交互式对话接口模块

提供命令行交互界面，支持用户与RAG系统进行流畅对话。
包含会话管理、命令解析、历史记录等功能。
"""

import sys
import os
from typing import List, Dict, Optional, Callable
from datetime import datetime

# 跨平台readline支持
try:
    import readline  # Unix/Linux/macOS
except ImportError:
    try:
        import pyreadline3 as readline  # Windows
    except ImportError:
        readline = None  # 没有readline支持

from ..retrieval import rag_engine
from ..config import config


class ChatInterface:
    """交互式对话接口，提供用户友好的命令行交互体验"""

    def __init__(self):
        """初始化对话接口"""
        self.session_history: List[Dict[str, str]] = []
        self.max_history = 50  # 最大历史记录数量
        self.commands = {
            '/help': self.show_help,
            '/history': self.show_history,
            '/clear': self.clear_history,
            '/exit': self.exit_chat,
            '/info': self.show_system_info,
            '/sources': self.toggle_sources_mode,
            '/stats': self.show_statistics
        }
        self.show_sources = False  # 是否显示来源信息
        self.running = True

    def display_welcome(self) -> None:
        """显示欢迎信息"""
        welcome_msg = """
╔══════════════════════════════════════════════════════════════╗
║                    🤖 RAG 智能对话系统                        ║
║                                                              ║
║  基于检索增强生成的智能问答系统                                ║
║  输入问题开始对话，输入 /help 查看帮助命令                      ║
╚══════════════════════════════════════════════════════════════╝
        """
        print(welcome_msg)

    def show_help(self, args: List[str] = None) -> None:
        """显示帮助信息"""
        help_msg = """
📚 可用命令:
────────────────────────────────────────────────────────────
/help          - 显示此帮助信息
/history       - 显示对话历史
/clear         - 清空对话历史
/sources       - 切换是否显示来源信息
/info          - 显示系统信息
/stats         - 显示查询统计
/exit 或 quit  - 退出对话系统

💡 使用技巧:
────────────────────────────────────────────────────────────
• 直接输入问题即可开始对话
• 使用上下箭头键浏览历史输入
• 支持中英文混合查询
• 输入的问题越具体，回答越准确
        """
        print(help_msg)

    def show_history(self, args: List[str] = None) -> None:
        """显示对话历史"""
        if not self.session_history:
            print("📝 暂无对话历史")
            return

        print("\n📝 对话历史:")
        print("─" * 60)
        for i, record in enumerate(self.session_history[-10:], 1):  # 显示最近10条
            timestamp = record.get('timestamp', '未知时间')
            question = record.get('question', '')
            print(f"{i:2d}. [{timestamp}] {question}")

    def clear_history(self, args: List[str] = None) -> None:
        """清空对话历史"""
        self.session_history.clear()
        print("🗑️  对话历史已清空")

    def show_system_info(self, args: List[str] = None) -> None:
        """显示系统信息"""
        print("\n💻 系统信息:")
        print("─" * 50)
        print(config)
        print(rag_engine)

    def toggle_sources_mode(self, args: List[str] = None) -> None:
        """切换来源显示模式"""
        self.show_sources = not self.show_sources
        mode = "开启" if self.show_sources else "关闭"
        print(f"🔍 来源信息显示: {mode}")

    def show_statistics(self, args: List[str] = None) -> None:
        """显示查询统计"""
        total_queries = len(self.session_history)
        if total_queries == 0:
            print("📊 暂无查询统计")
            return

        print(f"\n📊 查询统计:")
        print("─" * 30)
        print(f"总查询数: {total_queries}")
        print(f"平均查询长度: {self._calculate_avg_query_length():.1f} 字符")

    def _calculate_avg_query_length(self) -> float:
        """计算平均查询长度"""
        if not self.session_history:
            return 0.0

        total_length = sum(len(record.get('question', ''))
                          for record in self.session_history)
        return total_length / len(self.session_history)

    def process_command(self, user_input: str) -> bool:
        """
        处理用户命令

        Args:
            user_input: 用户输入

        Returns:
            bool: True表示继续运行，False表示退出
        """
        parts = user_input.strip().split()
        command = parts[0].lower()
        args = parts[1:] if len(parts) > 1 else []

        if command in self.commands:
            self.commands[command](args)
            return True
        elif command in ['exit', 'quit']:
            self.exit_chat()
            return False
        else:
            print(f"❓ 未知命令: {command}，输入 /help 查看帮助")
            return True

    def process_query(self, query: str) -> None:
        """
        处理用户查询

        Args:
            query: 查询文本
        """
        if not query.strip():
            print("⚠️  请输入有效的查询内容")
            return

        print(f"\n🤔 正在思考: {query}")
        print("⏳ 正在查询...")

        try:
            if self.show_sources:
                # 显示详细查询结果
                result = rag_engine.query_with_sources(query)
                self._display_detailed_result(result)
            else:
                # 显示简洁查询结果
                response = rag_engine.query(query)
                print(f"\n🤖 回答:")
                print("─" * 50)
                print(str(response))

            # 记录查询历史
            self._record_query(query, str(response))

        except Exception as e:
            print(f"❌ 查询失败: {e}")
            print("💡 建议检查系统状态或重新尝试")

    def _display_detailed_result(self, result: Dict[str, any]) -> None:
        """
        显示详细的查询结果

        Args:
            result: 查询结果字典
        """
        print(f"\n🤖 回答:")
        print("─" * 50)
        print(result['answer'])

        if result['sources']:
            print(f"\n📚 参考来源 (共{len(result['sources'])}个):")
            print("─" * 50)
            for i, source in enumerate(result['sources'], 1):
                score = source.get('score', 0)
                score_text = f" (相关性: {score:.4f})" if score else ""
                print(f"{i}. {source['text'][:100]}...{score_text}")

    def _record_query(self, question: str, answer: str) -> None:
        """
        记录查询到历史

        Args:
            question: 问题
            answer: 回答
        """
        timestamp = datetime.now().strftime("%H:%M:%S")
        record = {
            'timestamp': timestamp,
            'question': question,
            'answer': answer[:100] + "..." if len(answer) > 100 else answer
        }

        self.session_history.append(record)

        # 限制历史记录数量
        if len(self.session_history) > self.max_history:
            self.session_history = self.session_history[-self.max_history:]

    def exit_chat(self, args: List[str] = None) -> None:
        """退出对话"""
        print("\n👋 感谢使用RAG智能对话系统，再见！")
        self.running = False

    def get_user_input(self, prompt: str = "💬 您的问题: ") -> str:
        """
        获取用户输入

        Args:
            prompt: 输入提示符

        Returns:
            str: 用户输入
        """
        try:
            return input(prompt).strip()
        except KeyboardInterrupt:
            print("\n\n👋 检测到中断信号，正在退出...")
            self.exit_chat()
            return ""
        except EOFError:
            print("\n\n👋 输入结束，正在退出...")
            self.exit_chat()
            return ""

    def run(self) -> None:
        """运行交互式对话循环"""
        self.display_welcome()

        # 配置readline的自动补全和历史功能
        if readline:
            try:
                readline.read_history_file()
            except FileNotFoundError:
                pass

        while self.running:
            user_input = self.get_user_input()

            if not user_input or not self.running:
                continue

            # 检查是否是命令
            if user_input.startswith('/'):
                self.process_command(user_input)
            else:
                # 处理查询
                self.process_query(user_input)

            print("\n" + "─" * 60 + "\n")

        # 保存历史记录
        if readline:
            try:
                readline.write_history_file()
            except:
                pass


def start_interactive_chat() -> None:
    """启动交互式对话"""
    chat = ChatInterface()
    chat.run()


if __name__ == "__main__":
    start_interactive_chat()